package com.seed.core.pojo.seed;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.seed.core.pojo.Const;
import com.seed.core.annotation.BelongsTo;

import java.util.HashMap;
import java.util.Map;

@JsonInclude(JsonInclude.Include.NON_NULL)
public class BelongsTos extends Relation {

    public BelongsTos of(Map<Class<?>, Seed> seeds, Class<?> selfEntityClass, Class<?> targetEntityClass, BelongsTo belongsTo) {
        setSelfSeed(seeds.get(selfEntityClass));
        setTargetSeed(seeds.get(targetEntityClass));
        setTargetSeedName(targetSeed.getName());

        setSelfEntityClass(selfEntityClass);
        setTargetEntityClass(targetEntityClass);

        setSelfColumn(belongsTo.selfColumn());
        setTargetColumn(belongsTo.targetColumn());
        setLabel(belongsTo.label());
        setComment(belongsTo.comment());

        setExtra(belongsTo.extra());

        return this;
    }

    @Override
    public BelongsTos clone() {
        BelongsTos ret = new BelongsTos();
        ret.setTargetSeedName(targetSeedName);
        ret.setSelfSeed(selfSeed);
        ret.setTargetSeed(targetSeed);
        ret.setSelfEntityClass(selfEntityClass);
        ret.setTargetEntityClass(targetEntityClass);
        ret.setSelfColumn(selfColumn);
        ret.setTargetColumn(targetColumn);
        ret.setLabel(label);
        ret.setComment(comment);

        if(extra != null) ret.setExtra(new HashMap<>(extra));

        return ret;
    }

    @Override
    public Seed getExtraSeed() {
        return selfSeed;
    }

    public String inferSelfColumn() {
        if(StrUtil.isBlank(selfColumn)) return StrUtil.toUnderlineCase(StrUtil.lowerFirst(targetSeed.getName())) + '_' + Const.ID;

        return StrUtil.toUnderlineCase(selfColumn);
    }

    public String inferTargetColumn() {
        if(StrUtil.isBlank(targetColumn)) return Const.ID;

        return StrUtil.toUnderlineCase(targetColumn);
    }

//    public QueryCondition getQueryCondition(String basePath, String cross) {
//        String selfTableAlias = StrKit.selfTableAlias(basePath);
//        String targetTableAlias = StrKit.targetTableAlias(basePath, cross);
//        return getQueryCondition(selfTableAlias, selfTableAlias, targetTableAlias);
//    }
}
